package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.common.Result.PageResult;
import com.blog.common.constant.MessageConstant;
import com.blog.common.exception.LoginFailedException;
import com.blog.common.exception.RegisterException;
import com.blog.dto.UserDto;
import com.blog.dto.UserRegisterDto;
import com.blog.entity.User;
import com.blog.service.IUserService;
import com.blog.mapper.UserMapper;
import com.blog.vo.UserGetInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService{


    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 用户登录
     * @param userDto
     * @return
     */
    @Override
    public User login(UserDto userDto) {
        //取出用户名和密码
        String FUsername = userDto.getUsername();
        String FPassword = userDto.getPassword();
        //根据用户名查询用户信息
        //构建查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,FUsername);
        User user = getOne(queryWrapper);
        //判断用户是否存在
        if (user == null){
            throw new LoginFailedException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //判断密码是否正确，将密码进行MD5加密处理后再进行比对
        FPassword = DigestUtils.md5DigestAsHex(FPassword.getBytes());
        if (!user.getPassword().equals(FPassword)){
            throw new LoginFailedException(MessageConstant.PASSWORD_ERROR);
        }
        //全部校验通过，返回用户信息
        return user;
    }

    /**
     * 用户注册
     * @param userRegisterDto
     */
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //获取用户名和密码
        String FPassword = userRegisterDto.getPassword();
        //比对两次的密码是否一致
        if (!FPassword.equals(userRegisterDto.getConfirmPassword())){
            throw new RegisterException(MessageConstant.PASSWORD_NOT_MATCH);
        }
        //判断验证码是否与redis中一致，取出验证码
        String redisCode = (String) redisTemplate.opsForValue().get(userRegisterDto.getEmail());
        //取出前端的验证码
        String FCode = userRegisterDto.getCode();
        if (redisCode == null){
            throw new RegisterException(MessageConstant.CODE_NOT_FOUND);
        }
        if (!redisCode.equalsIgnoreCase(FCode)){
            throw new RegisterException(MessageConstant.CODE_ERROR);
        }
        //将密码进行MD5加密处理
        FPassword = DigestUtils.md5DigestAsHex(FPassword.getBytes());
        //构建用户对象
        User user = new User();
        BeanUtils.copyProperties(userRegisterDto,user);
        //设置密码
        user.setPassword(FPassword);
        //将用户信息保存到数据库
        save(user);
        //删除redis中的验证码
        redisTemplate.delete(userRegisterDto.getEmail());
    }

    /**
     * 获取用户列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult getUsers(Integer pageNum, Integer pageSize) {
        //准备分页参数
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(User::getCreateTime);
        //执行分页查询
        Page<User> page = page(new Page<>(pageNum, pageSize), queryWrapper);
        Page<User> result = page(page, queryWrapper);

        //转换成vo
        List<UserGetInfoVo> list = result.getRecords().stream().map(user -> {
            UserGetInfoVo userGetInfoVo = new UserGetInfoVo();
            BeanUtils.copyProperties(user, userGetInfoVo);
            return userGetInfoVo;
        }).toList();
        //封装返回结果
        return new PageResult(result.getTotal(), list);
    }
}
